//
//  KuaixunListViewController.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/6/2.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import HandyJSON
import PullToRefresh

class KuaixunListViewController: UIViewController ,SliderGalleryControllerDelegate, UITableViewDelegate, UITableViewDataSource  {

    var tableView: UITableView!
    var searchView: UIView?
    var maskView: UIView?
    let banner = SliderGalleryPresenter()
    var pageNum = 0
    var bannerModels : [YSBanner] = []
    var models:[KuaixunModel] = []
    let bottomRefreher = PullToRefresh(position: .bottom)
    let segment = UISegmentedControl(frame: CGRect(x: 0, y: 0, width: 200, height: 28))
    var listType = 0
    var startTimeLabel:UILabel?
    var endTimeLabel:UILabel?
    var channelLabel:UILabel?
    var startTime = ""
    var endTime = ""
    let timePicker = UIDatePicker(frame: CGRect(x: 0, y: Const.SCREEN_HEIGHT-260, width: Const.SCREEN_WIDTH, height: 260))
    let bgView = UIView(frame: CGRect(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT))
    var channels = ""
    
    deinit {
        if let head = tableView.topPullToRefresh{
            self.tableView.removePullToRefresh(at: .top)
        }
        if let btm = tableView.bottomPullToRefresh{
            self.tableView.removePullToRefresh(at: .bottom)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT), style: .plain)
        self.view.addSubview(self.tableView)
        
        banner.delegate = self
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorStyle = .none
        self.title = "快讯"
        self.setupPullToRefresh()
        self.refresh()

        KuaixunModel.readListFromPersistence()
        self.requestBanner()
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "搜索", style: .plain, target: self, action: #selector(KuaixunListViewController.search))
        
        self.segment.segmentTitles = ["我的快讯","全部快讯"]
        self.segment.addTarget(self, action: #selector(KuaixunListViewController.onChooseSegement(_:)), for: .valueChanged)
        self.navigationItem.titleView = self.segment
        self.segment.selectedSegmentIndex = 0
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tableView.reloadData()
    }
    
    func setupPullToRefresh() {
        self.tableView.addPullToRefresh(PullToRefresh()) { [weak self] in
            self?.refresh()
        }
        self.addRefreshFooter()
    }
    
    func addRefreshFooter() -> Void {
        self.tableView.addPullToRefresh(bottomRefreher) { [weak self] in
            if self == nil {
                return
            }
            self!.loadmore()
        }
    }

    @objc func onChooseSegement(_ sender: UISegmentedControl) {
        
        if listType == sender.selectedSegmentIndex {
            return
        }
        listType = sender.selectedSegmentIndex
        self.refresh();
    }
    
    func refresh() {
        var params : [String : String] = [:]
        if listType == 1 && self.channels.count == 0{
            params = ["page":"1"]
        }else{
            let idList = self.channels.count == 0 ? User.get.channels : self.channels
            params = ["names":idList,"page":"1"]
        }
        params["starttime"] = self.startTime
        params["endtime"] = self.endTime
        
        _ = NetworkManager.GET(NetworkManager.Kuaixun_LIST,params: params) {
            (status, response) in
            //            result.get("pic")
            //            updateBanner(pics);
            if status {
                let newKuaixuns = response.wtmList.map({ (dic) -> KuaixunModel in
                    let kx = JSONDeserializer<KuaixunModel>.deserializeFrom(dict:dic as? NSDictionary)!
                    kx.updateIsRead()
                    return kx
                })
                self.models.removeAll()
                self.models.append(contentsOf: newKuaixuns)
                self.pageNum = 2
                DispatchQueue.main.async {
                    self.stopLoading()
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func loadmore() {
        let pageNumStr = String(pageNum)
        let idList = User.get.channels
        var params : [String : String] = [:]
        if listType == 0 {
            params = ["names":idList,"page":pageNumStr]
        }else{
            params = ["page":pageNumStr]
        }
//        let params = ["names":idList,"page":pageNumStr]
        params["starttime"] = self.startTime
        params["endtime"] = self.endTime
        
        _ = NetworkManager.GET(NetworkManager.Kuaixun_LIST,params: params) {
            (status, response) in
            //            result.get("pic")
            //            updateBanner(pics);
            if status {
                let newKuaixuns = response.wtmList.map({ (dic) -> KuaixunModel in
                    JSONDeserializer<KuaixunModel>.deserializeFrom(dict:dic as? NSDictionary)!
                })
                self.models.append(contentsOf: newKuaixuns)
                self.pageNum += 1
                DispatchQueue.main.async {
                    self.stopLoading()
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func stopLoading(){
        tableView.endRefreshing(at: .top)
        tableView.endRefreshing(at: .bottom)
    }
    
    func requestBanner() {
        
        _ = NetworkManager.GET(NetworkManager.ZIXUN_Banner) { (status, response) in
            //            result.get("pic")
            //            updateBanner(pics);
            if status {
                let pics = response.wtmList
                self.bannerModels = pics.map({ (dic) -> YSBanner in
                    JSONDeserializer<YSBanner>.deserializeFrom(dict:dic as? NSDictionary)!
                })
                self.banner.setupViews()
            }
        }
    }
    
    // MARK:- banner delegate
    //获取数据源
    func galleryDataSource()->[String] {
        return self.bannerModels.map{
            $0.url
        }
    }
    //获取内部scrollerView的宽高尺寸
    func galleryScrollerViewSize()->CGSize {
        return CGSize.init(width: Const.SCREEN_WIDTH, height: Const.SCREEN_WIDTH * 0.432)
    }
    
    func galleryViewTapped(_ index:Int) {
        let vc:ImageViewController = UIStoryboard.init(name: "mainStoryBoard", bundle: Bundle.main).instantiateViewController(withIdentifier: ImageViewController.VCID) as! ImageViewController
        vc.imageUrl = self.bannerModels[index].url
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    // MARK :- tableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return models.count + 1
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return Const.SCREEN_WIDTH * 0.432 + Const.ONE_PIXEL;
        }else {
            let Kuaixun = models[indexPath.row - 1]
            return self.heightOfKuaixun(Kuaixun)
        }
    }
    
    func heightOfKuaixun(_ zx: KuaixunModel) -> CGFloat {
        
        return KuaixunCell.heightWith(zx.title!)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let reuseId = "banner"
            if let cell = tableView.dequeueReusableCell(withIdentifier: reuseId) {
                return cell
            }
            let cell = UITableViewCell.init(style: .default, reuseIdentifier: reuseId)
            cell.contentView.backgroundColor = Const.WTM_GRAY
            cell.contentView.addSubview(banner.view)
            return cell
        }else {
            if let cell:KuaixunCell = tableView.dequeueReusableCell(withIdentifier: "KuaixunCell") as? KuaixunCell {
                let kx = self.models[indexPath.row - 1]
                cell.setTitle( kx.title! )
                cell.dateLabel.text = kx.getTime()
                cell.loveCount.text = kx.favourateCount
                cell.setUnread(!kx.isRead)
                return cell
            }
            let cell = KuaixunCell.init(style: .default, reuseIdentifier: "KuaixunCell")
            let kx = self.models[indexPath.row - 1]
            cell.setTitle( kx.title! )
            cell.dateLabel.text = kx.getTime()
            cell.loveCount.text = kx.favourateCount
            cell.selectionStyle = .none
            cell.setUnread(!kx.isRead)
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            return
        }
        let cell : KuaixunCell = tableView.cellForRow(at: indexPath) as! KuaixunCell
        let kx = self.models[indexPath.row - 1]
        var url = NetworkManager.BASE_URL + NetworkManager.Kuaixun_Detail + kx.modelId!
        url = NetworkManager.BASE_URL + NetworkManager.Kuaixun_Share + "id="+kx.modelId! //NetworkManager.BASE_URL + NetworkManager.Kuaixun_Share + "id="+kx.modelId!+"&iscome=1"
        
        let vc:WebViewController = UIStoryboard.init(name: "mainStoryBoard", bundle: Bundle.main).instantiateViewController(withIdentifier: WebViewController.VCID) as! WebViewController
        vc.url = url
        kx.setRead()
        vc.shareObj = ShareObject.init()
        vc.shareObj?.image = nil
        vc.shareObj?.imageUrl = "http://www.yunshutech.com/pictureService/showImage.action?type=0&filename=ccbe074f-b85f-454b-bc25-b1f977046222.png"
        vc.shareObj?.url = url + "&iscome=1"

        vc.shareObj?.title = cell.titleLabel.text!
        vc.title = "快讯详情"
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func subscribe(){
        let vc = KXChannelVC.init()
        let ary = User.get.channels.components(separatedBy: ",")
        vc.selected = ary.filter({ s in
            s.count > 0
        })
        vc.onComplete = { result in
           self.submit(result)
        }
        self.navigationController?.pushViewController(vc, animated: true)

    }
    
    func submit(_ result:String) {
        User.get.channels = result
        User.get.update() {isSuccess , response in
            if isSuccess {
                self.navigationController?.view.makeToast("定制成功！")
                self.refresh()
            }
            else{
                self.navigationController?.view.makeToast("修改失败，请稍后重试！")
            }
        }
    }
    
    @objc func search() {
        if self.searchView == nil {
            
            self.searchView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Int(Const.SCREEN_WIDTH), height: 269))
            self.searchView?.backgroundColor = Const.WTM_WHITE_SMOKE
            
            let tileLabel = UILabel(frame: CGRect(x: 0, y: 20, width: Const.SCREEN_WIDTH, height: 49))
            tileLabel.text = "请选择搜索条件"
            tileLabel.textAlignment = .center
            self.searchView?.addSubview(tileLabel)
            
            let line0 = UIView(frame: CGRect(x: 0, y: 64 , width: Const.SCREEN_WIDTH, height: Const.ONE_PIXEL))
            line0.backgroundColor = Const.WTM_WHITE_SMOKE;
            self.searchView?.addSubview(line0)
            
            self.startTimeLabel = self.addItem("开始时间：",atY: 64)
            let tap1 = UITapGestureRecognizer(target: self, action: #selector(KuaixunListViewController.chooseTime1))
            self.startTimeLabel?.addGestureRecognizer(tap1)
            
            self.endTimeLabel = self.addItem("结束时间：",atY: 116)
            let tap2 = UITapGestureRecognizer(target: self, action: #selector(KuaixunListViewController.chooseTime2))
            self.endTimeLabel?.addGestureRecognizer(tap2)
            
            self.channelLabel = self.addItem("类别：",atY: 168)
            let tap3 = UITapGestureRecognizer(target: self, action: #selector(KuaixunListViewController.chooseChannel))
            self.channelLabel?.addGestureRecognizer(tap3)
            
            let line2 = UIView(frame: CGRect(x: 0, y: 220, width: Const.SCREEN_WIDTH, height: Const.ONE_PIXEL))
            line2.backgroundColor = Const.WTM_WHITE_SMOKE;
            self.searchView?.addSubview(line2)
            
            let btn4 = UIButton.init(frame: CGRect.init(x: 0, y: 220, width: Int(Const.SCREEN_WIDTH/2), height: 49))
            btn4.backgroundColor = Const.WTM_WHITE_SMOKE
            btn4.addTarget(self, action: #selector(KuaixunListViewController.cancelSearch), for: .touchUpInside)
            btn4.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            btn4.setTitleColor(Const.WTM_BLACK, for: .normal)
            btn4.setTitle("取消", for: .normal)
            self.searchView?.addSubview(btn4)
            
            let btn5 = UIButton.init(frame: CGRect.init(x: Int(Const.SCREEN_WIDTH/2), y: 220, width: Int(Const.SCREEN_WIDTH)/2 + 1, height: 49))
            btn5.backgroundColor = Const.WTM_GREEN
            btn5.addTarget(self, action: #selector(KuaixunListViewController.confirmSearch), for: .touchUpInside)
            btn5.titleLabel?.font = UIFont.systemFont(ofSize: 14)
            btn5.setTitleColor(UIColor.white, for: .normal)
            btn5.setTitle("确定", for: .normal)
            self.searchView?.addSubview(btn5)
            
            maskView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: Const.SCREEN_WIDTH, height: Const.SCREEN_HEIGHT))
            maskView?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.4)
            maskView?.addSubview(self.searchView!)
        }
        self.view.addSubview(maskView!)
    }
    
    func addItem(_ name : String , subtitle:String? = nil , atY:CGFloat ) ->UILabel{
        let container = UIView.init(frame: CGRect.init(x: 0, y: atY, width: Const.SCREEN_WIDTH, height: 52))
        container.backgroundColor = UIColor.white
        container.tag = 99
        let titleLabel = UILabel.init(frame: CGRect.init(x: 15, y: 0, width: 290, height: 52))
        titleLabel.text = name
        titleLabel.isUserInteractionEnabled = true
        container.addSubview(titleLabel)
        
        let line = UIView.init(frame: CGRect.init(x: 0, y: 52 - Const.ONE_PIXEL, width: Const.SCREEN_WIDTH, height: Const.ONE_PIXEL))
        line.backgroundColor = Const.WTM_LIGHTGRAY
        container.addSubview(line)
        
        let arrow = UIImageView.init(frame: CGRect.init(x: Const.SCREEN_WIDTH - 40 , y: 11, width: 30, height: 30))
        arrow.image = UIImage.init(named: "right_arrow")
        container.addSubview(arrow)
        
        if let title2 = subtitle {
            let l = UILabel.init(frame: CGRect.init(x: Const.SCREEN_WIDTH - 200, y: 0, width: 160, height: 52))
            l.text = title2
            l.textAlignment = .right
            l.textColor = Const.WTM_GRAY
            container.addSubview(l)
        }
        self.searchView?.addSubview(container)
        return titleLabel
    }
    
    @objc func cancelSearch() {
        self.maskView?.removeFromSuperview()
    }
    
    @objc func confirmSearch() {
        self.refresh()
        self.maskView?.removeFromSuperview()
    }
    
    @objc func chooseTime1() {
        self.selectTime(true)
    }
    
    @objc func chooseTime2() {
        self.selectTime(false)
    }
    
    @objc func chooseChannel() {
        let vc = KXChannelVC.init()
        let ary = User.get.channels.components(separatedBy: ",")
        vc.selected = ary.filter({ s in
            s.count > 0
        })
        vc.onComplete = { result in
            self.channels = result
            self.channelLabel?.text = "类别：" + result
            self.refresh()
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func selectTime(_ isStartTime: Bool) {
        if timePicker.superview == nil {
            timePicker.frame = CGRect.init(x:0, y:Const.SCREEN_HEIGHT - 216, width:Const.SCREEN_WIDTH, height:216);
            timePicker.backgroundColor = Const.WTM_LIGHTGRAY
            timePicker.datePickerMode = .dateAndTime
            timePicker.autoresizingMask = UIView.AutoresizingMask.flexibleWidth;
            //        datePicker.showsSelectionIndicator = true
            
            
        }
        _ = bgView.subviews.map { view in
            view.removeFromSuperview()
        }
        let bar = UIView(frame: CGRect(x: 0, y: Const.SCREEN_HEIGHT - 266, width: Const.SCREEN_WIDTH, height: 50))
        bar.backgroundColor = UIColor.white
        let cancel = UIButton(type: .roundedRect)
        cancel.frame = CGRect(x: 10, y: 5, width: 80, height: 40)
        cancel.setTitle("取消", for: .normal)
        cancel.addTarget(self, action: #selector(KuaixunListViewController.hideTimePicker), for: .touchUpInside)
        bar.addSubview(cancel)
        
        let ok = UIButton(type: .roundedRect)
        ok.frame = CGRect(x: Const.SCREEN_WIDTH - 90, y: 5, width: 80, height: 40)
        ok.setTitle("确定", for: .normal)
        if isStartTime {
            ok.addTarget(self, action: #selector(KuaixunListViewController.corfirmTime1), for: .touchUpInside)
        }else {
            ok.addTarget(self, action: #selector(KuaixunListViewController.corfirmTime2), for: .touchUpInside)
        }
        bar.addSubview(ok)
        bgView.addSubview(bar)
        bgView.addSubview(timePicker)
        bgView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, transparency: 0.6)
        self.navigationController?.view.addSubview(bgView)
        
        let now = Date()
        timePicker.setDate(now, animated: false)
        self.navigationController?.view.addSubview(bgView)
    }
    
    @objc func hideTimePicker() {
        bgView.removeFromSuperview()
    }
    
    @objc func corfirmTime1() {
        bgView.removeFromSuperview()
        let date = timePicker.date
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
        let time = dateFormatter.string(from: date)
        self.startTimeLabel?.text = "开始时间：" + time
        self.startTime = time
    }
    @objc func corfirmTime2() {
        bgView.removeFromSuperview()
        let date = timePicker.date
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
        let time = dateFormatter.string(from: date)
        self.endTimeLabel?.text = "结束时间：" + time
        self.endTime = time
    }
}
